// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <melon/benchmark.h>
#include <melon/init/init.h>

#include <pollux/functions/macros.h>
#include <pollux/functions/registerer.h>
#include <pollux/functions/lib/benchmarks/FunctionBenchmarkBase.h>
#include <pollux/functions/prestosql/registration/registration_functions.h>

using namespace kumo::pollux;
using namespace kumo::pollux::exec;

namespace {

class RowFunctionBenchmark : public functions::test::FunctionBenchmarkBase {
 public:
  RowFunctionBenchmark() : FunctionBenchmarkBase() {
    functions::prestosql::registerAllScalarFunctions();
  }

  void run(const std::string& expr) {
    melon::BenchmarkSuspender suspender;
    vector_size_t size = 1'000;

    auto row_vector = vectorMaker_.row_vector({
        vectorMaker_.flat_vector<int64_t>(size, [](auto row) { return row; }),
        vectorMaker_.flat_vector<double>(
            size, [](auto row) { return row * 0.1; }),
    });

    auto exprSet = compileExpression(expr, row_vector->type());
    suspender.dismiss();

    int cnt = 0;
    for (auto i = 0; i < 100; i++) {
      cnt += evaluate(exprSet, row_vector)->size();
    }
    melon::doNotOptimizeAway(cnt);
  }
};

BENCHMARK(noCopy) {
  RowFunctionBenchmark benchmark;
  benchmark.run("row_constructor(c0, c1)");
}

BENCHMARK(copyMostlyFlat) {
  RowFunctionBenchmark benchmark;
  benchmark.run(
      "if(c0 > 100, row_constructor(c0, c1), row_constructor(1, 0.1))");
}

BENCHMARK(copyMostlyConst) {
  RowFunctionBenchmark benchmark;
  benchmark.run(
      "if(c0 < 100, row_constructor(c0, c1), row_constructor(1, 0.1))");
}

} // namespace

int main(int argc, char** argv) {
  melon::Init init{&argc, &argv};

  melon::runBenchmarks();
  return 0;
}
